package com.buildings;

import android.Manifest;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.buildings.base.BaseActivity;
import com.buildings.permissions.Acp;
import com.buildings.permissions.AcpListener;
import com.buildings.permissions.AcpOptions;
import com.buildings.util.DialogUtils;
import com.buildings.util.GPSUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class MainActivity extends BaseActivity implements View.OnClickListener {

    private WebView webView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        askMultiPermission();
    }

    public void initView(){
        TextView title = findViewById(R.id.tv_title);
        title.setText("选择建筑物");
        findViewById(R.id.iv_back).setOnClickListener(this);
        webView = findViewById(R.id.webview);
        webView.setHorizontalScrollBarEnabled(false);//水平不显示
        webView.setVerticalScrollBarEnabled(false); //垂直不显示
        WebSettings webSettings = webView.getSettings();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webSettings.setJavaScriptEnabled(true);//启用js
        webSettings.setBlockNetworkImage(false);//解决图片不显示
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.setDomStorageEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webView.getSettings().setAllowFileAccessFromFileURLs(true);
        webView.getSettings().setGeolocationDatabasePath( getFilesDir().getPath() );
        webSettings.setDatabaseEnabled(true);//
        webSettings.setGeolocationEnabled(true);//
        webView.addJavascriptInterface(new MyJavaInterface(),"androidObject");
//支持缩放，默认为true。
        webSettings.setSupportZoom(true);
//调整图片至适合webview的大小
        webSettings.setUseWideViewPort(true);
// 缩放至屏幕的大小
        webSettings.setLoadWithOverviewMode(true);
//设置默认编码
        webSettings.setDefaultTextEncodingName("utf-8");
////设置自动加载图片
        webSettings.setLoadsImagesAutomatically(true);

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError errorResponse) {
                super.onReceivedError(view, request, errorResponse);
            }
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                //6.0以下执行
                //网络未连接
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

        });
        webView.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
            }

            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);
            }
        });
        webView.loadUrl("file:///android_asset/map.html");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_back:
                finish();
                break;
        }
    }


    public class MyJavaInterface {

        @JavascriptInterface
        public void androidMapClick(final String lng, final String lat){
            //横竖屏切换  0竖屏   1横屏 somehowTheScreen
            Log.e("经纬度",lng+","+lat);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //dialog选择建筑类型
                    DialogUtils.showBuildSelectDialog(activity, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            int type = (int) v.getTag();
                            String iconUrl = "";
                            switch (type){
                                case 1:
                                    //城镇住宅
                                    iconUrl = "images/ic_town_house.png";
                                    break;
                                case 2:
                                    //城镇非住宅
                                    iconUrl = "images/ic_town_no_house.png";
                                    break;
                                case 3:
                                    //农村住宅
                                    iconUrl = "images/ic_village_house.png";
                                    break;
                                case 4:
                                    //农村公共建筑
                                    iconUrl = "images/ic_village_public_build.png";
                                    break;
                            }

                            //此处请求接口，新的表单

                            //在地图标记对应建筑116.288  40.1543
                            webView.loadUrl("javascript:addIconMarker('"+lng+"','"+lat+"','"+iconUrl+"')");
//                            webView.loadUrl("javascript:addIconMarker('116.288','40.1543','http://api.tianditu.gov.cn/img/map/markerA.png')");
                        }
                    },true);

                }
            });

        }
    }


    private AMapLocationClient  mlocationClient;
    /**
     * 高德定位
     */
    private void geocodeLocation(){
        //声明mlocationClient对象
        //声明mLocationOption对象
        Log.e("geocodeLocation","开始定位");
        AMapLocationClientOption mLocationOption = null;
        mlocationClient = new AMapLocationClient(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位监听
        mlocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                Log.e("TAG","定位结果"+aMapLocation.getErrorCode());
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        //定位成功回调信息，设置相关消息
                        aMapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                        double latitude = aMapLocation.getLatitude();//获取纬度
                        double longitude = aMapLocation.getLongitude();//获取经度
                        double[] a = GPSUtil.gcj02_To_Gps84(latitude,longitude);
//        double[] a =  GPSUtil.gps84_To_Gcj02(39.92361,116.38094);
                        Log.e("lat","lat=" +a[0]);
                        Log.e("lon","lon=" +a[1]);
                        aMapLocation.getAccuracy();//获取精度信息
                        String province = aMapLocation.getProvince();
                        String city = aMapLocation.getCity();
                        String district = aMapLocation.getDistrict();
                        String street = aMapLocation.getStreet();
                        String detail = aMapLocation.getDescription();
//                        String message = "javascript:"+Constant.JS_FUNC_GEOGRAPHICAL_LOCATION+"('"+longitude+"','"+latitude+"','"+aMapLocation.getCity()+"')";
                        Log.e("TAG","定位 = province="+province+" city="+city+" district="+district+" street = "+street+" detail= "+detail);
                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date date = new Date(aMapLocation.getTime());
                        df.format(date);//定位时间
//                        webView.loadUrl("javascript:addMarker("+a[1]+","+a[0]+")");
                        Message message = Message.obtain();
                        message.obj = a;
                        handler.sendMessageDelayed(message,5000);
                        mlocationClient.stopLocation();
                        return;
                    } else {
                        //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
//                        Log.e("AmapError","location Error, ErrCode:"
//                                + aMapLocation.getErrorCode() + ", errInfo:"
//                                + aMapLocation.getErrorInfo());
                    }
                }

            }
        });
//设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
//设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
// 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
// 在定位结束后，在合适的生命周期调用onDestroy()方法
// 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
//启动定位
        mlocationClient.startLocation();

    }

    private void askMultiPermission() {
        Acp.getInstance(this).
                request(new AcpOptions.Builder()
                                .setPermissions(
//                                        Manifest.permission.CAMERA,
                                        Manifest.permission.READ_EXTERNAL_STORAGE,
                                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                        //                               Manifest.permission.RECEIVE_SMS,
                                        Manifest.permission.ACCESS_FINE_LOCATION,
                                        Manifest.permission.ACCESS_COARSE_LOCATION
//                                        Manifest.permission.RECORD_AUDIO
                                )

                                /*以下为自定义提示语、按钮文字
                                .setDeniedMessage()
                                .setDeniedCloseBtn()
                                .setDeniedSettingBtn()
                                .setRationalMessage()
                                .setRationalBtn()*/

                                .build(),
                        new AcpListener() {
                            @Override
                            public void onGranted() {
                                initView();
//                                geocodeLocation();
                            }

                            @Override
                            public void onDenied(List<String> permissions) {

                            }
                        });
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            double[] a = (double[]) msg.obj;
//            webView.loadUrl("javascript:addMarker("+a[1]+","+a[0]+")");
        }
    };

}
